package com.jake.xpage.page;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.CallSuper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public abstract class XPageActivity extends AppCompatActivity implements IXPageConfigHandler {
    protected XPageContainer mContentView;
    protected IXPageConfigHandler mPageConfigHandler;

    protected IXPageConfigHandler createPageConfig() {
        return new DefaultPageConfigHandler();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContentView = new XPageContainer(createMainPage(this));
        mContentView.setPageConfigHandler(this);
        getLifecycle().addObserver(mContentView.getLifecycleObserver());
        setContentView(mContentView);
        mContentView.setHost(new XPageContainer.IHost() {
            @Override
            public void closeContainer() {
                finish();
            }
        });
        mPageConfigHandler = createPageConfig();
    }

    @Override
    public void configPage(@NonNull XPage page, @NonNull XPageConfig config) {
        if (mPageConfigHandler != null) {
            mPageConfigHandler.configPage(page, config);
        }
    }

    protected abstract XPage createMainPage(@NonNull Context context);

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mContentView.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        mContentView.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @CallSuper
    @Override
    public void onBackPressed() {
        if (!mContentView.onBackPressed()) {
            super.onBackPressed();
        }
    }
}
